﻿using System;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using System.Text;

namespace CEFdemo
{
    public class CSfunctionAsyn
    {
        public async Task<string> getverificationcode(string email)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string[] message = new string[] { "0011", "getvercode", encryptedEmail };
            string tostring = string.Join(",", message);
            Client client = new Client();
            return await client.SendMessageAsync(tostring);
        }
        
        public async Task<string> newuser(string email, string password, string code)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string encryptedPassword = ClientEncryption.Encrypt(password);
            string encryptedCode = ClientEncryption.Encrypt(code);
            string[] message = new string[] { "0011", "register", encryptedEmail, encryptedPassword, encryptedCode};
            string tostring = string.Join(",", message);
            Client client = new Client();
            return await client.SendMessageAsync(tostring);
        }
        
        public async Task<string> loginmd(string email, string password)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string encryptedPassword = ClientEncryption.Encrypt(password);
            string[] message = new string[] { "0011", "login", encryptedEmail, encryptedPassword};
            string tostring = string.Join(",", message);
            Client client = new Client();
            string response = await client.SendMessageAsync(tostring);
            if (response == "402" || response == "404")
            {
                return response;
            }
            else
            {
                return cloudfileitem(response);
            }
        }
        
        public async Task<string> uploadfile(string email, string filepath, string filename)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string encryptedFilename = ClientEncryption.Encrypt(filename);
            string[] message = new string[] { "0011", "uploadfile", encryptedEmail, encryptedFilename };
            string tostring = string.Join(",", message);
            Client client = new Client();
            string response = await client.SendMessageAsync(tostring);
            if (response == "200")
            {
                using (FileStream fileStream = File.OpenRead(filepath))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        await client.SendFileAsync(buffer.Take(bytesRead).ToArray());
                    }
                }
                byte[] eof = Encoding.UTF8.GetBytes("EOF");
                await client.SendFileAsync(eof);
                string filelist  = await client.RecevieResponse();
                return cloudfileitem(filelist);
            }
            else
            {
                return "UploadError";
            }
        }

        public string cloudfileitem(string filelist)
        {
            string[] filePathArray = filelist.Split(',');
            string div = "";
            foreach (var file in filePathArray)
            {
                div += $"<li class=\"list-group-item list-group-item-light\">" +
                       $"<span>{file}</span>" +
                       $"<div class=\"btn-group\">" +
                       $"<button class=\"btn-custom\" onclick=\"downloadfile(this.name)\" name={file}>" +
                       $"<img src=\"static/svg/cloud-download.svg\" alt=\"Bootstrap\" width=\"20px\" height=\"20px\"></button>" +
                       $"<button class=\"btn-custom\" onclick=\"deletecloudfile(this.name)\" name={file}> " +
                       $"<img src=\"static/svg/trash.svg\" alt=\"Bootstrap\" width=\"20px\" height=\"20px\">" +
                       $"</button></div></li>";
            }
            return div;
        }

        public async Task<string> deletecloudfile(string email,string filename)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string encryptedFilename = ClientEncryption.Encrypt(filename);
            string[] message = new string[] { "0011", "deletefile", encryptedEmail, encryptedFilename};
            string tostring = string.Join(",", message);
            Client client = new Client();
            string response = await client.SendMessageAsync(tostring);
            if(response == "405"){
                return "DeleteError";
            }
            else if(response == "406")
            {
                return "";
            }
            else
            {
                return cloudfileitem(response);
            }
        }

        public async Task downloadfile(string email, string filename, string downloadselect, string currentpath, string downloadfolder)
        {
            string encryptedEmail = ClientEncryption.Encrypt(email);
            string encryptedFilename = ClientEncryption.Encrypt(filename);
            string[] message = new string[] { "0011", "downloadfile", encryptedEmail, encryptedFilename };
            string tostring = string.Join(",", message);
            Client client = new Client();

            byte[] data = Encoding.UTF8.GetBytes(tostring);
            await client.stream.WriteAsync(data, 0, data.Length);

            string localFilePath;
            switch (downloadselect)
            {
                case "0":
                    localFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\" + filename;
                    break;
                case "1":
                    localFilePath = currentpath + "\\" + filename;
                    break;
                case "2":
                    localFilePath = downloadfolder + "\\" + filename;
                    break;
                default:
                    localFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads\\" + filename;
                    break;
            }
            

            using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = new byte[1024];
                int readCount;
                while ((readCount = await client.stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    // Check for EOF signal in the data
                    string dataReceived = Encoding.UTF8.GetString(buffer, 0, readCount);
                    if (dataReceived.Contains("EOF"))
                    {
                        break;
                    }
                    await fileStream.WriteAsync(buffer, 0, readCount);
                }
            }
        }
    }
}